﻿@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>编码管理</title>
    <link href="~/scripts/layui-v2.5.6/layui/css/layui.css" rel="stylesheet" />
    <script src="https://cdn.jsdelivr.net/npm/jsbarcode@3.11.5/dist/JsBarcode.all.min.js"></script>
    <style>
        .layui-form { padding: 10px 0; }
        .search-box { 
            background-color: #fff;
            padding: 10px;
            margin-bottom: 10px;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        .search-item {
            display: inline-flex;
            align-items: center;
            margin-right: 10px;
        }
        .search-item label {
            margin-right: 8px;
            color: #333;
            font-size: 14px;
            white-space: nowrap;
        }
        .search-item .layui-input {
            width: 200px;
            display: inline-block;
        }
        .search-item .layui-form-select {
            width: 200px;
            display: inline-block;
        }
        .search-item .layui-form-select dl {
            max-height: 200px;
        }
        .search-item .layui-form-select .layui-input {
            width: 200px;
            display: inline-block;
        }
        .search-btn {
            background-color: #1E9FFF;
            border-color: #1E9FFF;
        }
        .reset-btn {
            background-color: transparent;
            border: 1px solid #ddd;
            color: #666;
        }
        .table-box { margin: 15px 0; }
        .layui-btn-sm { margin: 0 5px; }
        .layui-table-tool { padding: 10px; }
        .required:after {
            content: "*";
            color: red;
            margin-right: 5px;
            position: absolute;
            left: 5px;
        }
        .layui-form-label {
            position: relative;
            padding-left: 15px;
        }
        .layui-form-item .layui-input-inline {
            margin-right: 0;
        }
        #addForm {
            max-width: 800px;
            margin: 0 auto;
        }
        .layui-textarea {
            min-height: 60px;
        }
    </style>
</head>
<body>
    <!-- 搜索区域 -->
    <div class="layui-form search-box">
        <div class="search-item">
            <label>条码类型</label>
            <div class="layui-input-inline">
                <select name="codeType" lay-filter="codeType" lay-verify="required">
                    <option value="">请选择条码类型</option>
                    <option value="物料产品条码">物料产品条码</option>
                    <option value="包装条码">包装条码</option>
                    <option value="库存条码">库存条码</option>
                    <option value="设备码">设备码</option>
                    <option value="工作站码">工作站码</option>
                    <option value="仓库码">仓库码</option>
                </select>
            </div>
        </div>
        <div class="search-item">
            <label>业务编码</label>
            <input type="text" name="businessCode" class="layui-input" placeholder="请输入业务编码">
        </div>
        <div class="search-item">
            <label>业务名称</label>
            <input type="text" name="businessName" class="layui-input" placeholder="请输入业务名称">
        </div>
        <div class="search-item">
            <button class="layui-btn search-btn" lay-submit lay-filter="searchBtn">
                <i class="layui-icon">&#xe615;</i>查询
            </button>
            <button type="reset" class="layui-btn reset-btn" id="resetBtn">
                <i class="layui-icon">&#xe669;</i>重置
            </button>
        </div>
    </div>

    <!-- 工具栏 -->
    <div class="layui-btn-group">
        <button class="layui-btn layui-btn-sm" id="addBtn">
            <i class="layui-icon">&#xe654;</i> 新增
        </button>
        <button class="layui-btn layui-btn-sm layui-btn-danger" id="batchDeleteBtn">
            <i class="layui-icon">&#xe640;</i> 删除
        </button>
    </div>

    <!-- 数据表格 -->
    <div class="table-box">
        <table id="dataTable" lay-filter="dataTable"></table>
    </div>

    <!-- 新增编码弹窗 -->
    <div id="addForm" style="display: none; padding: 20px;">
        <form class="layui-form" lay-filter="addFormFilter">
            <div class="layui-form-item">
                <label class="layui-form-label required">条码格式</label>
                <div class="layui-input-inline" style="width: 200px;">
                    <select name="barFormat" lay-verify="required">
                        <option value="">请选择条码格式</option>
                        <option value="EAN码">EAN码</option>
                        <option value="QR二维码">QR二维码</option>
                        <option value="UPC码">UPC码</option>
                    </select>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label required">条码类型</label>
                <div class="layui-input-inline" style="width: 200px;">
                    <select name="barTypes" lay-verify="required" lay-filter="barTypesSelect">
                        <option value="">请选择条码类型</option>
                        <option value="物料产品条码">物料产品条码</option>
                        <option value="包装条码">包装条码</option>
                        <option value="库存条码">库存条码</option>
                        <option value="设备码">设备码</option>
                        <option value="工作站码">工作站码</option>
                        <option value="仓库码">仓库码</option>
                    </select>
                </div>
                <div class="layui-input-inline" style="width: auto;">
                    <label class="layui-form-label" style="width: auto; padding-left: 0;">是否启用</label>
                    <div class="layui-input-inline" style="margin-right: 0;">
                        <input type="radio" name="isNo" value="1" title="是" checked>
                        <input type="radio" name="isNo" value="0" title="否">
                    </div>
                </div>
            </div>
            <!-- 物料相关字段，默认隐藏 -->
            <div id="materialFields" style="display: none;">
                <div class="layui-form-item">
                    <label class="layui-form-label">物料编码</label>
                    <div class="layui-input-inline" style="width: 200px;">
                        <input type="text" name="businessCode" class="layui-input" placeholder="请选择物料编码">
                    </div>
                    <button type="button" class="layui-btn layui-btn-primary" id="selectMaterial">
                        <i class="layui-icon">&#xe615;</i>
                    </button>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">物料名称</label>
                    <div class="layui-input-block">
                        <input type="text" name="businessName" class="layui-input" readonly>
                    </div>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">条码内容</label>
                <div class="layui-input-block">
                    <textarea name="barContext" class="layui-textarea" style="min-height: 100px;" placeholder="请输入条码内容"></textarea>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">条码</label>
                <div class="layui-input-block">
                    <button type="button" class="layui-btn" id="generateBarcode">
                        <i class="layui-icon">&#xe654;</i>生成条码
                    </button>
                    <input type="hidden" name="barCode" id="barcodeValue">
                    <div id="barcodeContainer" style="margin-top: 10px; text-align: center; display: none;">
                        <svg id="barcode"></svg>
                    </div>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">备注</label>
                <div class="layui-input-block">
                    <textarea name="remark" class="layui-textarea" placeholder="请输入备注"></textarea>
                </div>
            </div>
            <div class="layui-form-item" style="text-align: center; margin-top: 30px;">
                <button class="layui-btn" lay-submit lay-filter="addSubmit">保存</button>
                <button type="button" class="layui-btn layui-btn-primary" onclick="layer.closeAll()">取消</button>
            </div>
        </form>
    </div>

    <script src="~/scripts/jquery-3.4.1.min.js"></script>
    <script src="~/scripts/layui-v2.5.6/layui/layui.js"></script>
    <script>
        layui.use(['table', 'form', 'layer'], function () {
            var table = layui.table;
            var form = layui.form;
            var layer = layui.layer;
            var $ = layui.$;
            
            // 重新渲染表单
            form.render('select');

            // 初始化表格
            var tableIns = table.render({
                elem: '#dataTable',
                url: '/CodingManagement/GetPagedList',
                method: 'get',
                toolbar: '#toolbarDemo',
                defaultToolbar: ['filter', 'exports', 'print'],
                page: true,
                parseData: function(res){
                    return {
                        "code": res.code,
                        "msg": res.msg,
                        "count": res.count,
                        "data": res.data
                    };
                },
                cols: [[
                    {type: 'checkbox', fixed: 'left'},
                    {field: 'barTypes', title: '条码类型', width: 120},
                    {field: 'barFormat', title: '条码格式', width: 120},
                    {field: 'barContext', title: '条码内容', width: 200},
                    {field: 'businessCode', title: '业务编码', width: 150},
                    {field: 'businessName', title: '业务名称', width: 150},
                    {field: 'barCode', title: '条码', width: 200, templet: function(d){
                        if (d.url) {
                            var imgUrl = d.url.startsWith('/') ? d.url : '/' + d.url;
                            if (imgUrl.endsWith('.svg')) {
                                imgUrl = imgUrl.replace('.svg', '.png');
                            }
                            return '<img src="' + imgUrl + '" style="max-width:150px;height:40px;cursor:pointer;" ' +
                                   'onclick="showBigImage(\'' + imgUrl + '\')" ' +
                                   'onerror="console.error(\'图片加载失败:\', this.src); this.style.display=\'none\'; this.parentElement.textContent=\'图片加载失败\';">';
                        } else if (d.barCode) {
                            return d.barCode;
                        }
                        return '';
                    }},
                    {field: 'isNo', title: '是否启用', width: 100, templet: function(d){
                        return d.isNo === 1 ? '<span class="layui-badge layui-bg-green">是</span>' : '<span class="layui-badge layui-bg-gray">否</span>';
                    }},
                    {field: 'operation', title: '操作', width: 120, templet: function(d){
                        return '<button class="layui-btn layui-btn-danger layui-btn-xs" lay-event="delete">' +
                               '<i class="layui-icon">&#xe640;</i>删除' +
                               '</button>';
                    }}
                ]],
                response: {
                    statusCode: 0
                },
                text: {
                    none: '暂无相关数据'
                },
                done: function() {
                    console.log('表格初始化完成');
                    // 确保表格实例可用
                    if (!window.tableIns) {
                        window.tableIns = this;
                    }
                }
            });

            // 搜索按钮事件
            form.on('submit(searchBtn)', function(data){
                tableIns.reload({
                    where: data.field,
                    page: { curr: 1 }
                });
                return false;
            });

            // 重置按钮事件
            $('#resetBtn').on('click', function(){
                // 重置表单字段
                $('.search-box select[name="codeType"]').val('');
                $('.search-box input[name="businessCode"]').val('');
                $('.search-box input[name="businessName"]').val('');
                form.render('select'); // 重新渲染select

                // 重新加载表格，清空搜索条件
                tableIns.reload({
                    where: {},
                    page: { curr: 1 }
                });
            });

            // 新增按钮事件
            $('#addBtn').on('click', function(){
                // 先重置表单内容
                var $form = $('#addForm');
                $form.find('input[type="text"], input[type="hidden"], textarea').val('');
                $form.find('select').val('');
                $form.find('input[type="radio"][value="1"]').prop('checked', true);
                
                // 清空条码显示
                var barcodeContainer = document.getElementById('barcodeContainer');
                if (barcodeContainer) {
                    barcodeContainer.style.display = 'none';
                    var svg = barcodeContainer.querySelector('svg');
                    if (svg) {
                        svg.innerHTML = '';
                    }
                }

                // 隐藏物料相关字段
                $('#materialFields').hide();

                // 重新渲染表单
                form.render();

                layer.open({
                    type: 1,
                    title: '新增编码',
                    area: ['850px', '90%'],
                    maxmin: true,
                    content: $('#addForm'),
                    success: function(layero, index) {
                        // 再次确保表单是空的
                        $form.find('input[type="text"], input[type="hidden"], textarea').val('');
                        $form.find('select').val('');
                        $form.find('input[type="radio"][value="1"]').prop('checked', true);
                        
                        // 重新渲染表单
                        form.render();
                        
                        // 调整内容区域的滚动
                        $(layero).find('.layui-layer-content').css({
                            'height': 'calc(100% - 43px)',
                            'overflow-y': 'auto'
                        });
                        
                        // 调整表单容器的内边距
                        $('#addForm').css({
                            'height': '100%',
                            'padding': '20px 20px 60px 20px'
                        });
                    }
                });
            });

            // 生成条码按钮点击事件
            $('#generateBarcode').on('click', function() {
                var barFormat = $('select[name="barFormat"]').val();
                if (!barFormat) {
                    layer.msg('请先选择条码格式');
                    return;
                }

                // 调用后端接口生成条码
                $.ajax({
                    url: '/CodingManagement/GenerateBarcode',
                    type: 'GET',
                    data: { barFormat: barFormat },
                    success: function(res) {
                        if (res.success) {
                            try {
                                $('#barcodeContainer').show();
                                // 清空之前的条码
                                $('#barcode').empty();
                                
                                // 生成新条码
                                JsBarcode("#barcode", res.data, {
                                    format: "CODE128",
                                    width: 2,
                                    height: 50,
                                    displayValue: true,
                                    margin: 10,
                                    background: "#ffffff"
                                });

                                // 将生成的条码值保存到隐藏输入框
                                $('#barcodeValue').val(res.data);
                                layer.msg('条码生成成功');
                            } catch(e) {
                                layer.msg('条码生成失败：' + e.message);
                                console.error('条码生成失败:', e);
                            }
                        } else {
                            layer.msg('条码生成失败');
                        }
                    },
                    error: function() {
                        layer.msg('条码生成请求失败');
                    }
                });
            });

            // 选择物料按钮点击事件
            $('#selectMaterial').on('click', function() {
                layer.open({
                    type: 1,
                    title: '物料产品选择',
                    area: ['1000px', '600px'],
                    content: `
                        <div style="padding: 15px;">
                            <!-- 搜索区域 -->
                            <form class="layui-form" id="materialSearchForm">
                                <div class="layui-form-item">
                                    <div class="layui-inline">
                                        <label class="layui-form-label">物料编码</label>
                                        <div class="layui-input-inline">
                                            <input type="text" name="materialCode" class="layui-input" placeholder="请输入物料编码">
                                        </div>
                                    </div>
                                    <div class="layui-inline">
                                        <label class="layui-form-label">物料名称</label>
                                        <div class="layui-input-inline">
                                            <input type="text" name="materialName" class="layui-input" placeholder="请输入物料名称">
                                        </div>
                                    </div>
                                    <div class="layui-inline">
                                        <button type="button" class="layui-btn" id="materialSearchBtn">
                                            <i class="layui-icon">&#xe615;</i> 搜索
                                        </button>
                                        <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                                    </div>
                                </div>
                            </form>
                            
                            <!-- 数据表格 -->
                            <table id="materialTable" lay-filter="materialTable"></table>
                        </div>
                    `,
                    success: function(layero, index) {
                        // 初始化表格
                        table.render({
                            elem: '#materialTable',
                            url: '/CodingManagement/GetMaterialProductList',
                            method: 'get',
                            page: true,
                            cols: [[
                                {type: 'radio'},
                                {field: 'materielCode', title: '物料编码', width: 120},
                                {field: 'materielName', title: '物料名称', width: 200},
                                {field: 'specifications', title: '规格型号', width: 120},
                                {field: 'unitsId', title: '单位', width: 80},
                                {field: 'materielType', title: '物料/产品', width: 100},
                                {field: 'category', title: '所属分类', width: 100},
                                {field: 'createTime', title: '创建时间', width: 160, templet: function(d){
                                    return d.createTime ? new Date(d.createTime).toLocaleString() : '';
                                }}
                            ]],
                            response: {
                                statusCode: 0
                            },
                            parseData: function(res) {
                                return {
                                    "code": res.code,
                                    "msg": res.msg,
                                    "count": res.count,
                                    "data": res.data
                                };
                            },
                            request: {
                                pageName: 'page',
                                limitName: 'limit'
                            },
                            height: 'full-200',
                            limit: 10,
                            limits: [10, 20, 30, 50],
                            text: {
                                none: '暂无相关数据'
                            }
                        });

                        // 搜索按钮点击事件
                        $('#materialSearchBtn').on('click', function() {
                            var materialCode = $('input[name="materialCode"]').val();
                            var materialName = $('input[name="materialName"]').val();
                            
                            table.reload('materialTable', {
                                where: {
                                    materialCode: materialCode,
                                    materialName: materialName
                                },
                                page: { curr: 1 }
                            });
                            return false;
                        });

                        // 监听表格行单选事件
                        table.on('radio(materialTable)', function(obj) {
                            // 将选中的物料信息填充到主表单
                            $('input[name="businessCode"]').val(obj.data.materielCode);
                            $('input[name="businessName"]').val(obj.data.materielName);

                            // 生成条码内容
                            var barFormat = $('select[name="barFormat"]').val();
                            var materialCode = obj.data.materielCode;
                            var currentDate = new Date();
                            var dateStr = currentDate.getFullYear().toString().substr(2) +
                                        padZero(currentDate.getMonth() + 1) +
                                        padZero(currentDate.getDate());
                            
                            // 根据不同条码格式生成不同的条码内容
                            var barcodeContent = '';
                            switch(barFormat) {
                                case 'EAN码':
                                    // EAN-13格式：前缀(2位) + 物料编码(6位) + 日期(4位) + 校验位(1位)
                                    barcodeContent = 'EN' + materialCode.substr(-6) + dateStr.substr(-4);
                                    // 补足12位（不含校验位）
                                    barcodeContent = barcodeContent.padEnd(12, '0');
                                    break;
                                case 'QR二维码':
                                    // QR格式：前缀 + 物料编码 + 日期 + 随机数
                                    var random = Math.floor(Math.random() * 1000).toString().padStart(3, '0');
                                    barcodeContent = 'QR' + materialCode + dateStr + random;
                                    break;
                                case 'UPC码':
                                    // UPC-A格式：前缀(1位) + 物料编码(5位) + 日期(4位) + 随机数(1位) + 校验位(1位)
                                    var random = Math.floor(Math.random() * 10);
                                    barcodeContent = '0' + materialCode.substr(-5) + dateStr.substr(-4) + random;
                                    // 补足11位（不含校验位）
                                    barcodeContent = barcodeContent.padEnd(11, '0');
                                    break;
                                default:
                                    // 默认格式：前缀 + 物料编码 + 日期
                                    barcodeContent = 'STD' + materialCode + dateStr;
                            }

                            // 填充条码内容
                            $('textarea[name="barContext"]').val(barcodeContent);

                            // 关闭弹窗
                            layer.close(index);
                        });

                        // 监听条码格式选择变化
                        form.on('select(barFormat)', function(data){
                            // 如果已经选择了物料，则重新生成条码内容
                            var materialCode = $('input[name="businessCode"]').val();
                            if(materialCode) {
                                var currentDate = new Date();
                                var dateStr = currentDate.getFullYear().toString().substr(2) +
                                            padZero(currentDate.getMonth() + 1) +
                                            padZero(currentDate.getDate());
                                
                                var barcodeContent = '';
                                switch(data.value) {
                                    case 'EAN码':
                                        barcodeContent = 'EN' + materialCode.substr(-6) + dateStr.substr(-4);
                                        barcodeContent = barcodeContent.padEnd(12, '0');
                                        break;
                                    case 'QR二维码':
                                        var random = Math.floor(Math.random() * 1000).toString().padStart(3, '0');
                                        barcodeContent = 'QR' + materialCode + dateStr + random;
                                        break;
                                    case 'UPC码':
                                        var random = Math.floor(Math.random() * 10);
                                        barcodeContent = '0' + materialCode.substr(-5) + dateStr.substr(-4) + random;
                                        barcodeContent = barcodeContent.padEnd(11, '0');
                                        break;
                                    default:
                                        barcodeContent = 'STD' + materialCode + dateStr;
                                }
                                
                                $('textarea[name="barContext"]').val(barcodeContent);
                            }
                        });

                        // 辅助函数：数字补零
                        function padZero(num) {
                            return num.toString().padStart(2, '0');
                        }
                    }
                });
            });

            // 新增表单提交
            form.on('submit(addSubmit)', function(data){
                // 获取条码SVG内容
                var svgElement = document.getElementById('barcode');
                if (!svgElement) {
                    layer.msg('请先生成条码');
                    return false;
                }

                var loading = layer.load(2);

                // 将SVG转换为Canvas，再转换为图片数据
                var svgData = new XMLSerializer().serializeToString(svgElement);
                var svg = new Blob([svgData], {type: 'image/svg+xml;charset=utf-8'});
                var url = URL.createObjectURL(svg);
                var img = new Image();
                
                img.onload = function() {
                    var canvas = document.createElement('canvas');
                    // 设置较高的分辨率以确保图片清晰度
                    var scale = 2;
                    canvas.width = img.width * scale;
                    canvas.height = img.height * scale;
                    var ctx = canvas.getContext('2d');
                    ctx.scale(scale, scale);
                    ctx.fillStyle = 'white';
                    ctx.fillRect(0, 0, canvas.width, canvas.height);
                    ctx.drawImage(img, 0, 0);
                    URL.revokeObjectURL(url);

                    // 将Canvas转换为PNG格式的Base64数据
                    var imageData = canvas.toDataURL('image/png');

                    // 发送图片数据到服务器
                    $.ajax({
                        url: '/CodingManagement/SaveBarcodeImage',
                        type: 'POST',
                        contentType: 'application/json',
                        data: JSON.stringify({ imageData: imageData }),
                        success: function(res) {
                            if (res.success) {
                                // 将图片URL添加到表单数据
                                var formData = data.field;
                                formData.url = res.url;
                                formData.barCode = $('#barcodeValue').val();
                                
                                // 提交表单数据
                                $.ajax({
                                    url: '/CodingManagement/Create',
                                    type: 'POST',
                                    contentType: 'application/json',
                                    data: JSON.stringify(formData),
                                    success: function (response) {
                                        layer.close(loading);
                                        if (response) {
                                            // 立即关闭弹窗
                                            layer.closeAll('page');
                                            
                                            // 清空搜索条件
                                            $('.search-box select[name="codeType"]').val('');
                                            $('.search-box input[name="businessCode"]').val('');
                                            $('.search-box input[name="businessName"]').val('');
                                            form.render('select'); // 重新渲染select
                                            
                                            // 立即重新加载表格数据
                                            if (tableIns) {
                                                tableIns.reload({
                                                    where: {}, // 清空搜索条件
                                                    page: {
                                                        curr: 1 // 重新从第一页开始
                                                    }
                                                });
                                            }
                                            
                                            // 重置表单和清空条码显示
                                            var formEl = document.getElementById('addForm');
                                            if (formEl) {
                                                formEl.reset();
                                                form.render();
                                            }
                                            var barcodeContainer = document.getElementById('barcodeContainer');
                                            if (barcodeContainer) {
                                                barcodeContainer.style.display = 'none';
                                                var svg = barcodeContainer.querySelector('svg');
                                                if (svg) {
                                                    svg.innerHTML = '';
                                                }
                                            }
                                            
                                            // 显示成功消息
                                            layer.msg('保存成功', { icon: 1 });
                                        } else {
                                            layer.msg('保存失败', { icon: 2 });
                                        }
                                    },
                                    error: function (xhr, status, error) {
                                        layer.close(loading);
                                        console.error('保存失败:', error);
                                        layer.msg('保存失败: ' + (xhr.responseJSON?.message || error), { icon: 2 });
                                    }
                                });
                            } else {
                                layer.close(loading);
                                layer.msg('条码图片保存失败：' + res.message, {icon: 2});
                            }
                        },
                        error: function(xhr, status, error) {
                            layer.close(loading);
                            console.error('条码图片保存失败:', error);
                            layer.msg('条码图片保存失败，请检查网络连接', {icon: 2});
                        }
                    });
                };

                img.onerror = function() {
                    layer.close(loading);
                    layer.msg('条码图片生成失败', {icon: 2});
                };

                img.src = url;
                return false;
            });

            // 批量删除按钮事件
            $('#batchDeleteBtn').on('click', function(){
                var checkStatus = table.checkStatus('dataTable');
                var data = checkStatus.data;
                if(data.length === 0){
                    layer.msg('请选择要删除的数据');
                    return;
                }
                
                layer.confirm('确定要删除选中的' + data.length + '条数据吗？', function(index){
                    var ids = data.map(function(item){ return item.id; });
                    // 调用删除接口
                    $.ajax({
                        url: '/api/CodingManagement/BatchDelete',
                        type: 'POST',
                        contentType: 'application/json',
                        data: JSON.stringify(ids),
                        success: function(res){
                            if(res.success){
                                layer.msg('删除成功');
                                tableIns.reload();
                            } else {
                                layer.msg('删除失败：' + res.message);
                            }
                        }
                    });
                    layer.close(index);
                });
            });

            // 表格工具条事件
            table.on('tool(dataTable)', function(obj){
                var data = obj.data;
                if(obj.event === 'delete'){
                    layer.confirm('确定要删除这条数据吗？', function(index){
                        $.ajax({
                            url: '/CodingManagement/Delete',
                            type: 'POST',
                            data: { id: data.id },
                            success: function(res){
                                if(res.success){
                                    layer.msg('删除成功', { icon: 1 });
                                    // 刷新表格
                                    tableIns.reload();
                                } else {
                                    layer.msg(res.message || '删除失败', { icon: 2 });
                                }
                            },
                            error: function(){
                                layer.msg('删除失败，请稍后重试', { icon: 2 });
                            }
                        });
                        layer.close(index);
                    });
                }
            });

            // 监听条码类型选择
            form.on('select(barTypesSelect)', function(data){
                var materialFields = $('#materialFields');
                if(data.value === '物料产品条码') {
                    materialFields.show();
                } else {
                    materialFields.hide();
                    // 清空物料相关字段
                    $('input[name="businessCode"]').val('');
                    $('input[name="businessName"]').val('');
                }
            });
        });

        // 显示大图
        window.showBigImage = function(src) {
            if (!src) {
                console.error('图片URL为空');
                return;
            }
            // 确保URL以/开头
            var imgUrl = src.startsWith('/') ? src : '/' + src;
            // 添加时间戳防止缓存
            var timestamp = new Date().getTime();
            var imgUrlWithTimestamp = imgUrl + '?t=' + timestamp;
            console.log('显示大图URL:', imgUrlWithTimestamp); // 调试日志
            
            // 先验证图片是否可访问
            var img = new Image();
            img.onload = function() {
                layer.open({
                    type: 1,
                    title: false,
                    closeBtn: 1,
                    shadeClose: true,
                    area: ['auto', 'auto'],
                    skin: 'layui-layer-nobg',
                    content: '<div style="text-align:center;"><img src="' + imgUrlWithTimestamp + '" style="max-width:90vw;max-height:90vh;"></div>'
                });
            };
            img.onerror = function() {
                console.error('大图加载失败:', imgUrlWithTimestamp);
                layer.msg('图片加载失败');
            };
            img.src = imgUrlWithTimestamp;
        };
    </script>
</body>
</html>
